package com.sip.stream.utils.zfy;

import android.util.Log;

import com.sip.stream.utils.zfy.consumer.IGSMediaObserver;
import com.sip.stream.utils.zfy.encoder.IGSNV12Consumer;

import io.reactivex.Single;
import io.reactivex.functions.Action;
import io.reactivex.subjects.BehaviorSubject;
import java.util.HashSet;
import java.util.Set;

public class GSNV12DataSource implements IGSNV12DataSource {
    private static final String TAG = "GSNV12DataSource";

    private BehaviorSubject<byte[]> captureBehaviorSubject;
    protected Set<IGSNV12Consumer> consumers = new HashSet();
    private int fps;
    private int height;
    private IGSMediaObserver<IGSNV12DataSource> observer;
    private int width;

    public GSNV12DataSource(int width, int height, int fps) {
        this.width = width;
        this.height = height;
        this.fps = fps;
    }

    @Override
    public int getWidth() {
        return this.width;
    }

    @Override
    public int getHeight() {
        return this.height;
    }

    @Override
    public int getFPS() {
        return this.fps;
    }

    @Override
    public void addConsumer(IGSNV12Consumer iGSNV12Consumer) {
        this.consumers.add(iGSNV12Consumer);
        iGSNV12Consumer.addObserver(this);
        Log.i(TAG, "consumers add " + this.consumers);
    }

    @Override
    public void addObserver(IGSMediaObserver<IGSNV12DataSource> iGSMediaObserver) {
        this.observer = iGSMediaObserver;
    }

    @Override
    public void addNV12Data(byte[] bArr, long j) {
        for (IGSNV12Consumer iGSNV12Consumer : this.consumers) {
            iGSNV12Consumer.onNV12Stream(bArr, j);
        }
        BehaviorSubject<byte[]> behaviorSubject = this.captureBehaviorSubject;
        if (behaviorSubject != null) {
            behaviorSubject.onNext(bArr);
        }
    }

    @Override
    public Single<byte[]> capture() {
        Log.i(TAG, "capture");
        BehaviorSubject<byte[]> behaviorSubject = this.captureBehaviorSubject;
        if (behaviorSubject != null) {
            return behaviorSubject.firstOrError();
        }
        BehaviorSubject<byte[]> create = BehaviorSubject.create();
        this.captureBehaviorSubject = create;
        return create.firstOrError().doFinally(new Action() {
            @Override
            public  void run() {
                GSNV12DataSource.this.m654xa6a970ac();
            }
        });
    }

    public  void m654xa6a970ac(){
        this.captureBehaviorSubject = null;
    }

    @Override
    public void removeConsumer(IGSNV12Consumer iGSNV12Consumer) {
        Log.i(TAG, "consumers remove " + iGSNV12Consumer);
        this.consumers.remove(iGSNV12Consumer);
        if (this.consumers.isEmpty()) {
            Log.i(TAG, "onStop");
            IGSMediaObserver<IGSNV12DataSource> iGSMediaObserver = this.observer;
            if (iGSMediaObserver != null) {
                iGSMediaObserver.onStop(this);
            }
        }
    }
}
